package com.example.tangyee.utils;

import android.os.AsyncTask;
import android.util.Log;

import com.example.tangyee.bean.Article;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetArticlesForType extends AsyncTask<Void, Void, List<Article>> {

    private static final String TAG = "GetArticles";

    private int page;
    private int pageSize;
    private int supCls;
    private int subCls;
    private OnPostExecute mExecute;

    private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);

    public GetArticlesForType(int page, int pageSize,int supCls, int subCls, OnPostExecute execute){
        this.page = page;
        this.pageSize = pageSize;
        this.mExecute = execute;
        this.supCls = supCls;
        this.subCls = subCls;
    }

    @Override
    protected List<Article> doInBackground(Void... voids) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .retryOnConnectionFailure(false)
                .build();

        StringBuilder stringBuilder = new StringBuilder(ConstantsUtil.GET_ARTICLES_FOR_TYPE);
        stringBuilder.append("page=" + page);
        stringBuilder.append("&pagesize=" + pageSize);
        stringBuilder.append("&supCls=" + supCls);
        stringBuilder.append("&subCls=" + subCls);
        Request request = new Request.Builder()
                .url(stringBuilder.toString())
                .build();

        String respStr = null;
        try {
            Response response = okHttpClient.newCall(request).execute();
            respStr = response.body().string();

            if (respStr == null) {
                return null;
            }
        } catch (IOException e) {
            Log.e(TAG, "doInBackground: ", e);
        }
        List<Article> items = new ArrayList<>();

        try {
            Log.i(TAG, "Received JSON: " + respStr);
            JSONArray jsonArray = new JSONArray(respStr);
            // 将json转成list
            parseItems(items, jsonArray);
        } catch (JSONException je) {
            Log.e(TAG, "Failed to parse JSON", je);
        }  catch (NullPointerException npe) {
            Log.e(TAG, "doInBackground: ", npe);
            return null;
        }

        return items;
    }

    @Override
    protected void onPostExecute(List<Article> articles) {
        mExecute.onPostExecute(articles);
    }

    private void parseItems(List<Article> items, JSONArray jsonArray) throws JSONException {
        for (int i = 0; i < jsonArray.length(); i ++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Article article = new Article();
            article.setImage(jsonObject.getString("image"));

            jsonObject = jsonObject.getJSONObject("knowledge");

            article.setKnowID(jsonObject.getInt("ID"));
            article.setTitle(jsonObject.getString("Title"));
            String s = jsonObject.getString("ReleaseDate");
            s = s.substring(6,s.length()-2);
            article.setReleaseDate(mSimpleDateFormat.format(new Date(Long.valueOf(s))));
            article.setSummary(jsonObject.getString("Summary"));
//            article.setAuthor(jsonObject.getString("AuthorID"));

            items.add(article);
        }
    }

    public void setOnPostExecute(OnPostExecute execute) {
        this.mExecute = execute;
    }

    public interface OnPostExecute {
        void onPostExecute(List<Article> articles);
    }
}
